package com.stream.utils.aop;

import com.alibaba.fastjson.JSON;
import com.stream.model.entity.SysLogEntity;
import com.stream.service.SysLogService;
import com.stream.utils.HttpContextUtils;
import com.stream.utils.IPUtils;
import com.stream.utils.ShiroUtils;
import com.stream.utils.annotation.SysLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * 记录系统操作日志，切面处理类
 * Created by yebaokang on 2017/5/22.
 */

@Aspect
@Component
public class SysLogAspect {
    @Autowired
    private SysLogService sysLogService;

    //当方法上有此注解时，激活此切入点
    @Pointcut("@annotation(com.stream.utils.annotation.SysLog)")
    public void logPointCut() {
    }

    @Before("logPointCut()")
    public void saveSysLog(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();

        SysLogEntity sysLog = new SysLogEntity();
        SysLog log = method.getAnnotation(SysLog.class);
        if (log != null) {
            sysLog.setOperation(log.value());
        }

        //请求方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + method + "()");

        //请求参数
        Object[] args = joinPoint.getArgs();
        String params = JSON.toJSONString(args[0]);
        sysLog.setParams(params);

        //获取request
        HttpServletRequest request = HttpContextUtils.getHttPServletRequest();
        //获取请求IP
        sysLog.setIp(IPUtils.getIpAddr(request));

        //获取用户名
        String userName = ShiroUtils.getUserEntity().getUsername();
        sysLog.setUserName(userName);

        sysLog.setCreateDate(new Date());
        sysLogService.save(sysLog);
    }
}
